package com.yangming.springboot.deepin.playTest;

import com.yangming.springboot.deepin.playTest.ConnectionDriver;
import java.sql.Connection;
import java.util.LinkedList;

/**
 * @创建人 ym
 * @创建时间 2021/4/8 0008
 * @描述
 **/
public class ConnectionPool {

    private LinkedList<Connection> pool = new LinkedList<Connection>();
    public ConnectionPool(int initialSize){
        if (initialSize > 0){
            for (int i=0; i<initialSize; i++){
                //初始化连接池，这个连接池就是一个自定义的链表数组而已
                pool.addLast(ConnectionDriver.createConnection());
            }
        }
    }

    public void releaseConnection(Connection connection){
        if (connection != null){
            //释放线程就是把初始化链表中的线程，取出后再加回来而已,同时向其他waiting状态的线程唤醒，同步去获取连接
            synchronized(pool){
                pool.addLast(connection);
                pool.notifyAll();
            }
        }
    }

    public Connection fetchConnection(long mill) throws InterruptedException{
        synchronized(pool){
            if (mill <= 0){
                while(pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else{
                long future = System.currentTimeMillis() + mill;
                long remaining = mill;
                while(pool.isEmpty() && remaining > 0){
                    pool.wait();
                    remaining = future - System.currentTimeMillis();
                }
                Connection result = null;
                if (!pool.isEmpty()){
                    result = pool.removeFirst();
                }
                return result;
            }
        }
    }

}
